package seedling_record

import (
	rich_err "app/error"
	"app/models"
	"app/service"
	"app/service/orders"
	"app/utils"
	"errors"
	"math"
	"strconv"

	"github.com/jinzhu/gorm"

	"github.com/gin-gonic/gin"
)

func Gets(context *gin.Context) ([]*models.SeedlingRecordDetail, *models.Pager, *rich_err.RichError) {
	base := models.Orm.Model(&models.SeedlingRecord{}).
		Select("seedling_record.*, greenhouse.name as greenhouse_name,  orders.name as orders_name").
		Joins("LEFT JOIN greenhouse ON seedling_record.greenhouse_id = greenhouse.id").
		Joins("LEFT JOIN orders ON seedling_record.order_id = orders.id")

	results, pager, err := service.GetDetails[models.SeedlingRecordDetail](context, base, models.SeedlingRecord{}.TableName(), map[string]string{"greenhouse_name": "greenhouse.name", "orders_name": "orders.name"})

	if err != nil {
		return nil, nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	return results, pager, nil
}

func Get(id string) (*models.SeedlingRecordDetail, *rich_err.RichError) {
	base := models.Orm.Model(&models.SeedlingRecord{}).
		Select("seedling_record.*, greenhouse.name as greenhouse_name,  orders.name as orders_name").
		Joins("LEFT JOIN greenhouse ON seedling_record.greenhouse_id = greenhouse.id").
		Joins("LEFT JOIN orders ON seedling_record.order_id = orders.id")

	result, err := service.GetDetail[models.SeedlingRecordDetail](id, base)

	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	return result, nil
}

func Create(context *gin.Context) (*models.SeedlingRecordDetail, *rich_err.RichError) {
	req := new(models.SeedlingRecordCore)
	if err := context.ShouldBindJSON(req); err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	data := models.SeedlingRecord{SeedlingRecordCore: *req}
	if data.Quantity == 0 {
		data.Quantity = data.TrayNumber * data.UnitNumber
	}
	result := models.Orm.Create(&data)
	if result.Error != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	err := orders.UpdateDeliveredQuantity(req.OrderID)
	if err != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	return Get(strconv.Itoa(data.ID))
}

func Update(context *gin.Context) (*models.SeedlingRecordDetail, *rich_err.RichError) {
	req := new(models.SeedlingRecordDelta)
	if err := context.ShouldBindJSON(req); err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}

	data, err := service.Get[models.SeedlingRecord](context)
	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	if req.OrderID != nil {
		data.OrderID = int(math.Round(req.OrderID.(float64)))
	}
	if req.GreenhouseID != nil {
		data.GreenhouseID = int(math.Round(req.GreenhouseID.(float64)))
	}
	if req.SeedlingDate != nil {
		data.SeedlingDate = utils.ToDateV2(req.SeedlingDate.(string))
	}
	if req.TrayNumber != nil {
		data.TrayNumber = int(math.Round(req.TrayNumber.(float64)))
	}
	if req.UnitNumber != nil {
		data.UnitNumber = int(math.Round(req.UnitNumber.(float64)))
	}
	// 计算 numbers改用盘总数*每盘数量
	if req.Quantity != nil {
		data.Quantity = int(math.Round(req.Quantity.(float64)))
	} else {
		data.Quantity = data.TrayNumber * data.UnitNumber
	}

	if req.DriverPhone != nil {
		data.DriverPhone = req.DriverPhone.(string)
	}
	if req.DriverName != nil {
		data.DriverName = req.DriverName.(string)
	}
	if req.DeliveryFee != nil {
		data.DeliveryFee = req.DeliveryFee.(float64)
	}
	if req.PaymentMethod != nil {
		data.PaymentMethod = int(math.Round(req.PaymentMethod.(float64)))
	}
	if req.Remark != nil {
		data.Remark = req.Remark.(string)
	}
	result := models.Orm.Save(data)
	if result.Error != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	err = orders.UpdateDeliveredQuantity(data.OrderID)
	if err != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	return Get(strconv.Itoa(data.ID))
}

func Delete(context *gin.Context) *rich_err.RichError {
	data, err := service.Get[models.SeedlingRecord](context)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil
		}
		return rich_err.NewError(rich_err.RequestInvalid, err)
	}
	result := models.Orm.Delete(data)
	if result.Error != nil {
		return rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	err = orders.UpdateDeliveredQuantity(data.OrderID)
	if err != nil {
		return rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	return nil
}
